package com.snda.dw.lidejia.nbthrift;

import com.snda.dw.lidejia.thriftgen.UserProfile;
import com.snda.dw.lidejia.thriftgen.UserStorage;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.thrift.TException;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Hello world!
 *
 */
public class Server {

    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private static final class UserStorageHandler implements UserStorage.Iface {

        private final Random random = new Random();

        @Override
        public void store(UserProfile user) throws TException {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public UserProfile retrieve(int uid) throws TException {
            LOGGER.info("Client connected");
            UserProfile profile = new UserProfile(1, "lidejia");
            if (random.nextBoolean()) {
                throw new TException("==!");
            }
            try {
                int time = random.nextInt(10);
                LOGGER.info(String.format("Start sleeping %ss", time));
                TimeUnit.SECONDS.sleep(time);
            } catch (InterruptedException ex) {
                LOGGER.error("Interrupted", ex);
            }
            return profile;
        }
    }

    public static void main(String[] args) {
        try {
            TServerTransport transport = new TServerSocket(8888);
            TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(transport);
            serverArgs.processor(new UserStorage.Processor<UserStorageHandler>(new UserStorageHandler()));
            TServer server = new TThreadPoolServer(serverArgs);
            LOGGER.info("Starting server");
            server.serve();
        } catch (TTransportException ex) {
            LOGGER.error("Thrift Error", ex);
        }
    }
}
